package com.irdstudio.efp.flow.api.rest;

import java.util.List;
import java.util.Objects;

import com.irdstudio.basic.framework.core.util.TimeUtil;
import com.irdstudio.efp.flow.service.FlowCommonService;
import com.irdstudio.efp.flow.service.FlowRepulseUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.*;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.irdstudio.basic.framework.core.constant.ApplicationConstance;
import com.irdstudio.basic.framework.core.constant.ResponseData;
import com.irdstudio.basic.framework.core.vo.EngineHttpRequestVO;
import com.irdstudio.basic.framework.web.util.HttpClientUtil;
import com.irdstudio.basic.sequence.service.facade.SequenceService;
import com.irdstudio.efp.console.common.ConsoleConstant;
import com.irdstudio.efp.console.service.facade.PubSysInfoService;
import com.irdstudio.efp.flow.common.constance.FlowConstance;
import com.irdstudio.efp.flow.executor.util.AbstractController;
import com.irdstudio.efp.flow.service.facade.BizFlowInfoService;
import com.irdstudio.efp.flow.service.facade.FlowUrlConfigService;
import com.irdstudio.efp.flow.service.vo.BizFlowInfoVO;
import com.irdstudio.efp.riskm.service.facade.CaseDistrRatioService;
import com.irdstudio.efp.riskm.service.vo.CaseDistrRatioVO;

@RestController
@RequestMapping("/api")
public class CaseDistrRatioFlowController extends AbstractController {

    private static Logger logger = LoggerFactory.getLogger(CaseDistrRatioFlowController.class);


    @Autowired
    @Qualifier("bizFlowInfoService")
    private BizFlowInfoService bizFlowInfoService;

    @Autowired
    @Qualifier("flowUrlConfigService")
    private FlowUrlConfigService flowUrlConfigService;

    @Autowired
    @Qualifier("pubSysInfoService")
    private PubSysInfoService pubSysInfoService;

    @Autowired
    @Qualifier("caseDistrRatioService")
    private CaseDistrRatioService caseDistrRatioService;

    @Autowired
    @Qualifier("dbSeqService")
    private SequenceService sequenceService;

    @Autowired
    private FlowCommonService flowCommonService;

    @Autowired
    @Qualifier("flowRepulseUtil")
    private FlowRepulseUtil flowRepulseUtil;

    /**
     * 案件分配比例审批流程
     *
     * @param caseDistrRatioVO
     * @return
     * @author liuty
     * @date 2019年9月12日 上午10:15:39
     * @version 0.1
     */
    @RequestMapping(value = "/case/distr/ratio/commit", method = RequestMethod.POST)
    public @ResponseBody
    ResponseData<Integer> submitFlowDemoApproval(@RequestBody List<CaseDistrRatioVO> caseDistrRatioVO) {
        int outputVo = 0;
        //提交生成版本号
        caseDistrRatioVO.forEach(item -> {
            if (item.getApprvSts().equals(ConsoleConstant.APRV_STATUS_05)) {
                flowRepulseUtil.cleanRepulseAllInfo(item.getCaseDistrAppNo());
            }
        });
        try {
            String seq = sequenceService.getSequence("VERSION_NO", null, null);
            for (CaseDistrRatioVO item : caseDistrRatioVO) {
                setUserInfoToVO(item);
                item.setVersionNo(seq);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

//	        if(cooprOrgType.equals("001")) {
//	        	BigDecimal prmCase = caseDistrRatioVO.getPrimCaseRatio();
//	        	BigDecimal sedCase = caseDistrRatioVO.getSecdCaseRatio();
//	        	BigDecimal thdCase = caseDistrRatioVO.getThdCaseRatio();
//	        	BigDecimal longAge = caseDistrRatioVO.getLongAgeCaseRatio();
//		       if(!(prmCase.equals(1)&&sedCase.equals(1)&&thdCase.equals(1)&&longAge.equals(1))) {
//		    	   outputVo = -1;
//		    	   return setResponseMessage(outputVo, "委外机构各案件占比或长账龄占比校验之和不为1，请重置案件占比");
//		       }
//	        }else if(cooprOrgType.equals("002")) {
//	        	BigDecimal caseRatio = caseDistrRatioVO.getCaseRatio();
//	        	if(!(caseRatio.equals(1))) {
//	        		outputVo = -1;
//			       return setResponseMessage(outputVo, "律师事务所机构案件占比校验之和不为1，请重置案件占比");
//	        	}
//	        }else {
//	        	BigDecimal caseRatio = caseDistrRatioVO.getCaseRatio();
//	        	if(!(caseRatio.equals(1))) {
//	        		outputVo = -1;
//			       return setResponseMessage(outputVo, "风险代理机构案件占比校验之和不为1，请重置案件占比");
//	        }
//	        }

//	        BigDecimal prmCase = new BigDecimal(0.000);
//	        BigDecimal sedCase = new BigDecimal(0.000);
//	        BigDecimal thdCase = new BigDecimal(0.000);
//	        for(int i = 0 ; i < caseDistrRatioVOs.size(); i++) {
//	        	prmCase.add(caseDistrRatioVOs.get(i).getPrimCaseRatio());
//	        	sedCase.add(caseDistrRatioVOs.get(i).getPrimCaseRatio());
//	        	thdCase.add(caseDistrRatioVOs.get(i).getPrimCaseRatio());
//	        }
//	        if(!(prmCase.equals(1)&&sedCase.equals(1)&&thdCase.equals(1))) {
//	        	outputVo = -1;
//	        	return setResponseMessage(outputVo, "案件占比总和不为1");
//	        }

        logger.info("即将发起案件分配比例审批流程，信息为:" + JSON.toJSONString(caseDistrRatioVO));
        // 事件ID
        String eventId = "mCaseDistrRatioEnter";
        String flowId = "FW20190927000000007";
        // 流程岗位校验 （加在定义完事件ID和流程ID之后 在发起流程之前）
        if (!flowCommonService.dutyFlowCheck(eventId,flowId)){
            outputVo = -1;
            return setResponseMessage(outputVo, "发起风险分类调整申请审批流程失败!原因: 流程岗位已失效");
        }
        for (CaseDistrRatioVO item : caseDistrRatioVO) {
            item.setApprvSts(ConsoleConstant.APRV_STATUS_02);
        }
        BizFlowInfoVO bizFlowInfoVO = new BizFlowInfoVO();
        bizFlowInfoVO.setBizFlowType(FlowConstance.BIZ_FLOW_TYPE_10);
        bizFlowInfoVO.setBizFlowId(flowId);
        List<BizFlowInfoVO> listFlow = bizFlowInfoService.queryBizFlowInfoByFlowType(bizFlowInfoVO);

        logger.info("查询到的业务流程参数为：" + JSONObject.toJSONString(listFlow));
        if (Objects.nonNull(listFlow) && listFlow.size() > 0) {
            bizFlowInfoVO = listFlow.get(0);
            flowId = bizFlowInfoVO.getBizFlowId();  // 得到业务流转ID
        } else {
            //提交失败 待发起
            for (CaseDistrRatioVO item : caseDistrRatioVO) {
                item.setApprvSts(ConsoleConstant.APRV_STATUS_01);
                caseDistrRatioService.updateByPk(item);
            }
            outputVo = -1;
            return setResponseMessage(outputVo, "未配置相关信息提交失败!");
        }
        EngineHttpRequestVO eVo = new EngineHttpRequestVO();
        // 业务法人机构
        eVo.setBizLagelOrgCode(this.getUserInfo().getOrgInfo().getOrgCode());
        // 业务流水号
        eVo.setE_bizSerno(caseDistrRatioVO.get(0).getVersionNo());
        eVo.setFlowId(flowId);
        //事件ID
        eVo.setData(caseDistrRatioVO);
        eVo.setEventId(eventId);
        eVo.setG_bizSerno(caseDistrRatioVO.get(0).getVersionNo());
        try {
            HttpClientUtil.callFlowEngine(flowUrlConfigService.getRestfulSyncStartEventUrl(), eVo, String.class);
            for (CaseDistrRatioVO item : caseDistrRatioVO) {
                item.setLastUpdateTime(TimeUtil.getCurrentDateTime());
                item.setLastUpdateUser(caseDistrRatioVO.get(0).getLoginUserId());
                outputVo = caseDistrRatioService.updateByPk(item);
            }
        } catch (Exception e) {
            // 发起失败
            e.printStackTrace();
            logger.error("CaseDistrRatioVO", e.getMessage());
            outputVo = -1;
            return setResponseMessage(outputVo, "发起案件分配比例审批流程失败!原因: " + e.getMessage());
        }
        return getResponseData(outputVo);
    }

    private ResponseData<Integer> setResponseMessage(Integer outputVo, String message) {
        ResponseData<Integer> responseData = new ResponseData<Integer>();
        responseData.setMessage(message);
        responseData.setCode(ApplicationConstance.FAILURE);
        responseData.setSuccess(true);
        return responseData;
    }

    @RequestMapping(value = "/case/distr/appr", method = RequestMethod.POST)
    public @ResponseBody
    ResponseData<List<CaseDistrRatioVO>> queryByVisionNo(@RequestBody CaseDistrRatioVO caseDistrRatioVO) {
        List<CaseDistrRatioVO> outputVo = caseDistrRatioService.queryByVersionNo(caseDistrRatioVO);
        if (outputVo.size() > 0) {
            return getResponseData(outputVo);
        } else {
            return null;
        }
    }
}
